package com.linked.pay.coupon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linked.pay.coupon.bean.param.CouponInfoListParam;
import com.linked.pay.coupon.bean.param.UserGetCouponParam;
import com.linked.pay.coupon.bean.po.CouponInfoPO;
import com.linked.pay.coupon.bean.po.UserCouponPO;
import com.linked.pay.coupon.bean.vo.UserCouponListVO;
import com.linked.pay.coupon.mapper.ICouponInfoMapper;
import com.linked.pay.coupon.mapper.IUserCouponMapper;
import com.linked.pay.coupon.service.ICouponHandleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author :dbq
 * @date : 2023/3/6 9:31
 * @description : desc
 */
@Slf4j
@Service
public class CouponHandleServiceImpl implements ICouponHandleService {

    private final ObjectMapper mapper;

    private final ICouponInfoMapper couponInfoMapper;

    private final IUserCouponMapper userCouponMapper;

    @Autowired
    public CouponHandleServiceImpl(ObjectMapper mapper, ICouponInfoMapper couponInfoMapper, IUserCouponMapper userCouponMapper) {
        this.mapper = mapper;
        this.couponInfoMapper = couponInfoMapper;
        this.userCouponMapper = userCouponMapper;
    }

    @Override
    public List<UserCouponListVO> queryUserCouponList(CouponInfoListParam param) throws Exception {
        return couponInfoMapper.queryUserCouponList(param);
    }

    @Override
    public List<CouponInfoPO> queryCouponInfoList() throws Exception {
        QueryWrapper<CouponInfoPO> wrapper = new QueryWrapper<>();
        wrapper.eq("data_status", 1);
        return couponInfoMapper.selectList(wrapper);
    }

    @Override
    public boolean addCouponInfo(CouponInfoPO param) throws Exception {
        return couponInfoMapper.insert(param) > 0;
    }

    @Override
    public boolean userGetCoupon(UserGetCouponParam param) throws Exception {
        UserCouponPO temp = new UserCouponPO();
        temp.setUserId(param.getUserId());
        temp.setCouponId(param.getCouponId());
        return userCouponMapper.insert(temp) > 0;
    }

    @Override
    public CouponInfoPO findCouponInfo(String couponId) {
        return couponInfoMapper.selectById(couponId);
    }

    @Override
    public boolean checkUserCoupon(String userId, String couponId) {
        QueryWrapper<UserCouponPO> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        wrapper.eq("coupon_id", couponId);
        wrapper.eq("if_used", 0);
        return userCouponMapper.selectCount(wrapper) > 0;
    }
}
